<?php 
/**
 * 后台订单管理
 * ==============================================
 * 版权所有 2016-2026
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * ==============================================
 * @date: 2016年7月1日
 * @author: Clear
 * @version:
 */

namespace Admin\Controller;

use Api\Service\OrderService;
use Think\Controller;

class ApiController extends Controller {

    /**
     * 接口控制器初始化 加载配置
     */
    protected function _initialize()
    {
        /* 读取数据库中的配置 */
        $config =   S('DB_CONFIG_DATA');
        if(!$config){
            $config =   api('Config/lists');
            S('DB_CONFIG_DATA',$config);
        }
        C($config); //添加配置
    }
    //获取商家列表，根据地区 分类 查询对应的商家
    /**
     * 获取商家列表
     */
    public function get_shop_list(){
        $keyword = I('post.keyword');
        $lat = I('post.lat');
        $lng = I('post.lng');
        $category_name = I('post.category_id');
        $region = I('post.region');
        $where = [];
        $where['status'] = array('eq','2');
        $where['title'] = array('like',"%{$keyword}%");
        if(!empty($category_name)) {
            if($category = M('category')->where(array('title'=>$category_name))->find()) {
                if(!empty($category)) {
                    $where['category'] = array('like',"%{$category['id']}%");
                }

            }
        }
        if(!empty($region)) {
            $where['area'] = array('eq',$region);
        }
        $list = [];
        if(!empty($lat) && !empty($lng)) {
            $list = M('shop')->where($where)->field("id,title,describe,title_img,(
    6371 * acos (
      cos ( radians({$lat}) )
      * cos( radians( latitude ) )
      * cos( radians( longitude ) - radians({$lng}) )
      + sin ( radians({$lat}) )
      * sin( radians( latitude ) )
    )
  ) AS distance")->order('distance asc')->select();
            foreach ($list as &$item) {
                $title_img = array_filter(explode(',',$item['title_img']));
                $item['img'] =SITE_URL.get_cover($title_img[0],'path');
                $item['left_count']=get_left_up_number($item['id'])+get_left_in_number($item['id']);
                $item['yue_number']=get_up_yue_in_number($item['id'])+get_in_yue_in_number($item['id']);
            }
        }

        $data['shop_list'] = $list;
        echo json_encode($data,JSON_UNESCAPED_UNICODE);
        exit();
        //接收关键字，经纬度然后搜索对应条件
        $keyword=I('post.keyword');
        $lat=I('post.lat');
        $lng=I('post.lng');
        $category_name=I('post.category_id');
        $category_id=M('category')->where(array('title'=>$category_name))->find();
        $category_id=$category_id['id'];
        $region=I('post.region');
        if($category_id){
            //查询分类商家
            $shop_list = M('shop')->where(array('status'=>2))->where("category like '%$category_id%'")->order('id asc')->select();
        }elseif($region){
            //查询地区 商家 
            $shop_list = M('shop')->where(array('status'=>2,'area'=>I('post.region')))->order('id asc')->select();
        }
        else{
            //查询所有商家
            $shop_list = M('shop')->where(array('status'=>2))->where("title like '%$keyword%'")->order('id asc')->select();
        }
        //echo $lat;echo $lng;

        //循环商家数组
        foreach ($shop_list as $key => $value) {
           $goods[$key]['id'] = $value['id'];
           $goods[$key]['title'] = $value['title'];
           $goods[$key]['describe'] = $value['describe'];
           $title_img=explode(',',$value['title_img']);
           $goods[$key]['img'] =SITE_URL.get_cover($title_img[0],'path');
           $goods[$key]['left_count']=get_left_up_number($value['id'])+get_left_in_number($value['id']);
           $goods[$key]['yue_number']=get_up_yue_in_number($value['id'])+get_in_yue_in_number($value['id']);
           $goods[$key]['distance'] = getDistance($lat,$lng,$value['latitude'],$value['longitude']);
           //$banner[$key]['ad_link'] = $value['ad_link'];
           //echo getDistance($lat,$lng,$value['latitude'],$value['longitude']);
        }
        //根据距离排序
        $sort = array(
            'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
            'field'     => 'distance',       //排序字段
        );
        $arrSort = array();
        foreach($goods AS $uniqid => $row){
            foreach($row AS $key=>$value){
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if($sort['direction']){
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $goods);
        }
        $data['shop_list']=$goods;
        echo json_encode($data);
    }
    //获取添加广告时的默认信息
    public function get_add_ad_info(){

        $select=I('post.select');
        $ad_type=explode(',',$select);
        $ad_type_name="";
        //获取选择广告模式名称

        foreach($ad_type as $v){
            $ad_info=M('ad_type')->where(array('id'=>$v))->find();
            $ad_type_name.=$ad_info['title'].' ';
        }

        $data['ad_type_name']=$ad_type_name;
        if(I('post.area')!=''){
            $shop_list=M('shop')->where(array('area'=>I('post.area')))->select();
        }else{
            $shop_list=M('shop')->select();
        }

        //查询所有商家
        
        $category = M('category')->where(array('pid'=>0))->select();
            //查询每个分类下的商家，用户点击不同分类显示不同商家
            foreach ($category as $key => $value) {
               $cate[$key]['id'] = $value['id'];
               $cate[$key]['name'] = $value['title'];
               $two_category = M('category')->where(array('pid'=>$value['id']))->field('id')->select();
               foreach ($two_category as $k => $v) {
                    foreach($shop_list as $k2=>$v2){
                        $p_array=explode(',',$v2['category']);
                        if($select==1){
                            //获取剩余曝光广告位和预约广告位
                            $left_up_number=get_left_in_number($v2['id']);
                            $yue_number=get_in_yue_in_number($v2['id']);
                        }else{
                            $left_up_number=get_left_up_number($v2['id']);
                            $yue_number=get_up_yue_in_number($v2['id']);
                        }
                        //var_dump($two_category);
                        //筛选当前分类下的商家
                        if(in_array($v['id'],$p_array)&&$left_up_number!=0){
                                $cate[$key]['data'][$k2]['id'] = $v2['id'];
                                $cate[$key]['data'][$k2]['name'] = $v2['title'];
                                $cate[$key]['data'][$k2]['yue_number'] = $yue_number;
                                $cate[$key]['data'][$k2]['left_number'] = $left_up_number;
                                $title_img=explode(',',$v2['title_img']);
                                $cate[$key]['data'][$k2]['img'] = SITE_URL.get_cover($title_img[0],'path');
                        }
                     }
                   //$banner[$key]['ad_link'] = $value['ad_link'];
                }
               //$banner[$key]['ad_link'] = $value['ad_link'];
            }
       
        $data['shop_store']=$cate;
        $put_money=M('config')->where(array('name'=>'PUT_MONEY'))->find();
        $data['put_money']=$put_money['value'];
        //引流模式下
        if($select==1){
            //获取引流最少投放天数，拼接结束时间
            $day=M('config')->where(array('name'=>'IN_LIMIT_DAY'))->find();
            $enddate=strtotime(I('post.startdate'))+$day['value']*24*60*60;
            $data['enddate']=date('Y-m-d',$enddate);
            $data['minday']=$day['value'];
            //查询定向引流投放最少红包金额和投放最少个数
            $minnumber=M('config')->where(array('name'=>'MIN_RED_NUMBER'))->find();
            $minmoney=M('config')->where(array('name'=>'MIN_RED_MONEY'))->find();
            $data['minnumber']=$minnumber['value'];
            $data['minmoney']=$minmoney['value'];
            //获取定向引流模板
            $temlist=M('template')->where(array('ad_type'=>1))->select();
            foreach($temlist as $k=>$v){
                $tem[$k]['id']=$v['img'];
                $tem[$k]['img']=SITE_URL.get_cover($v['img'],'path');
            }
            $data['tem']=$tem;
            
        }else{
            //查询定向曝光投放最低天数和根据用户选择开始时间计算结束时间
            $day=M('config')->where(array('name'=>'UP_LIMIT_DAY'))->find();
            $enddate=strtotime(I('post.startdate'))+$day['value']*24*60*60;
            $data['enddate']=date('Y-m-d',$enddate);
            $data['minday']=$day['value'];
            //查询定向曝光的模板
            $temlist=M('template')->where(array('ad_type'=>2))->select();
            foreach($temlist as $k=>$v){
                $tem[$k]['id']=$v['img'];
                $tem[$k]['img']=SITE_URL.get_cover($v['img'],'path');
            }
            $data['tem']=$tem;
        }
        echo json_encode($data);
    }
    //定向曝光根据用户选择的开始时间，根据系统设置最低投放天数计算结束时间
    public function get_enddate(){
        //配置表查询最低天数
        $day=M('config')->where(array('name'=>'UP_LIMIT_DAY'))->find();
            $enddate=strtotime(I('post.startdate'))+$day['value']*24*60*60;
        $data['enddate']=date('Y-m-d',$enddate);

        echo json_encode($data);
    }
     //定向引流根据用户选择的开始时间，根据系统设置最低投放天数计算结束时间
    public function get_in_enddate(){
        //配置表查询最低天数
        $day=M('config')->where(array('name'=>'IN_LIMIT_DAY'))->find();
            $enddate=strtotime(I('post.startdate'))+$day['value']*24*60*60;
        $data['enddate']=date('Y-m-d',$enddate);

        echo json_encode($data);
    }
    //获取店铺的名称标题
    public function get_shop_title(){
        $select=I('post.select');
        $ad_type=explode(',',$select);
        $ad_type_name="";
        foreach($ad_type as $v){
            $ad_info=M('shop')->where(array('id'=>$v))->find();
            $ad_type_name.=$ad_info['title'].' ';
        }
        $data['shop_name']=$ad_type_name;
        echo json_encode($data);
    }
    //获取店铺二级分类
    public function get_category(){
        $category = M('category')->where(array('pid'=>0))->select();
        foreach ($category as $key => $value) {
           $cate[$key]['id'] = $value['id'];
           $cate[$key]['name'] = $value['title'];
           $two_category = M('category')->where(array('pid'=>$value['id']))->select();
           foreach ($two_category as $k => $v) {
               $cate[$key]['data'][$k]['id'] = $v['id'];
               $cate[$key]['data'][$k]['name'] = $v['title'];
               $cate[$key]['data'][$k]['status'] = "";
               //$banner[$key]['ad_link'] = $value['ad_link'];
            }
           //$banner[$key]['ad_link'] = $value['ad_link'];
        }
        $data['category']=$cate;
        echo json_encode($data);
    }
    //用户申请商家入驻
    public function apply_shop(){
        $user_info=M('usermember')->where(array('openid'=>I('post.openid')))->find();
        $data['user_id']=$user_info['id'];
        $data['title']=I('post.title');
        $data['describe']=I('post.describe');
        $data['name']=I('post.name');
        $data['phone']=I('post.phone');
        $data['area']=I('post.area');
        $data['address']=I('post.address');
        $data['latitude']=I('post.latitude');
        $data['longitude']=I('post.longitude');
        $data['title_img']=I('post.title_img');
        $data['shop_img']=I('post.shop_img_id');
        $data['zheng_img']=I('post.zheng_img_id');
        $data['fan_img']=I('post.fan_img_id');
        $data['category']=I('post.category');
        $data['look_category']=I('post.look_category');
        $data['addtime']=time();
        $data['status']=1;
        $data['is_show']=I('post.is_show');
        $res=M('shop')->add($data);
    }
    //用户上传图片，返回上传图片id
    public function add_picture(){
        $file=$_FILES['uploadfile_ant'];
        $dir='./shop/'.date("Ymd").'/';
        $filename=$dir.md5(microtime(true)).'.'.explode('.',$file['name'])[count(explode('.',$file['name']))-1];
        if(!file_exists($_SERVER['DOCUMENT_ROOT'].$dir)){
             mkdir($_SERVER['DOCUMENT_ROOT'].$dir,0777,true);
        }

        if(move_uploaded_file($file['tmp_name'],$_SERVER['DOCUMENT_ROOT'].$filename)){

            if($info==""||$info==null){
                $data['path']=$filename;
                $data['url']=$filename;
            }else{
                $data['path']=$info.$filename;
                $data['url']=$filename;
            }
            //$data['goods_id']=$order_goods['goods_id'];
            $data['md5']=md5($data['path']);
            $data['sha1']=sha1($data['path']);
            $data['create_time']=time();
            $data['status']=1;

            $res=M("picture")->add($data);
            echo json_encode($res);
        }else{
            echo json_encode(2);
        }
    }
    //用户上传视频，返回上传视频id
    public function add_video(){
        $file=$_FILES['uploadfile_ant'];
        $dir='./shop/'.date("Ymd").'/';
        $filename=$dir.md5(microtime(true)).'.'.explode('.',$file['name'])[count(explode('.',$file['name']))-1];
        if(!file_exists($_SERVER['DOCUMENT_ROOT'].$dir)){
             mkdir($_SERVER['DOCUMENT_ROOT'].$dir,0777,true);
        }
        if(move_uploaded_file($file['tmp_name'],$_SERVER['DOCUMENT_ROOT'].$filename)){
            //var_dump($file);
            if($info==""||$info==null){
                $data['path']=$filename;
                $data['url']=$filename;
            }else{
                $data['path']=$info.$filename;
                $data['url']=$filename;
            }
            //$data['goods_id']=$order_goods['goods_id'];
            $data['md5']=md5($data['path']);
            $data['sha1']=sha1($data['path']);
            $data['create_time']=time();
            $data['status']=1;
            $res=M("picture")->add($data);
            echo json_encode($res);
        }else{
            echo json_encode(2);
        }
    }
    //首页加载数据
    public function index(){
        //设置广告的状态
        set_up_ad_status();
        //订单自动结算
        OrderService::autoSettlement();
        //获取banner
        $list = M('banner')->select();
        foreach ($list as $key => $value) {
           $banner[$key]['id'] = $value['id'];
           $banner[$key]['img'] = SITE_URL.get_cover($value['icon'],'path');
           //$banner[$key]['ad_link'] = $value['ad_link'];
        }
        $data['banner'] = $banner;

        //获取系统分类
        $category = M('category')->where(array('pid'=>0))->select();

        foreach ($category as $key => $value) {
           //$cate[$key] = $value['title'];
           $two_category=M('category')->where(array('pid'=>$value['id']))->select();
           foreach($two_category as $k=>$v){
            //$cate[$key]$value['title']['id']=$v['id'];
            $cate[$value['title']][$k]=$v['title'];
           }
           //$banner[$key]['ad_link'] = $value['ad_link'];
        }
        $data['category']=$cate;


        foreach ($category as $key => $value) {
           $cate1[$key] = $value['title'];
           //$banner[$key]['ad_link'] = $value['ad_link'];
        }
        $data['category1']=$cate1;
        //获取广告方式，暂时没用，只有定向引流和定向曝光
        $ad_type_list=M('ad_type')->select();
        $ad_type[0]='广告方式';
        foreach ($ad_type_list as $key => $value) {
           // $ad_type[$key]['id'] = $value['id'];
           // $ad_type[$key]['title'] = $value['title'];
            $ad_type[$key+1] = $value['title'];
           //$banner[$key]['ad_link'] = $value['ad_link'];
        }
        $data['ad_type']=$ad_type;

        $lat=I('post.lat');$lng=I('post.lng');
        //获取当前所有审核通过的商家
        $shop_list = M('shop')->where(array('status'=>2))->order('id asc')->select();
        foreach ($shop_list as $key => $value) {
           $goods[$key]['id'] = $value['id'];
           $goods[$key]['title'] = $value['title'];
           $goods[$key]['describe'] = $value['describe'];
           $title_img=explode(',',$value['title_img']);
           $goods[$key]['img'] =SITE_URL.get_cover($title_img[0],'path');
           $goods[$key]['left_count']=get_left_up_number($value['id'])+get_left_in_number($value['id']);
           $goods[$key]['yue_number']=get_up_yue_in_number($value['id'])+get_in_yue_in_number($value['id']);
           $goods[$key]['distance'] = getDistance($lat,$lng,$value['latitude'],$value['longitude']);
           //$banner[$key]['ad_link'] = $value['ad_link'];
        }
        //商家根据距离排序
        $sort = array(
        'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
        'field'     => 'distance',       //排序字段
        );
        $arrSort = array();
        foreach($goods AS $uniqid => $row){
            foreach($row AS $key=>$value){
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if($sort['direction']){
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $goods);
        }
        $data['shop_list']=$goods;
        $openid=I('post.openid');
        //echo $openid;
        $user_info=M('usermember')->where(array('openid'=>$openid))->field('id,username,head_icon')->find();

        $data['user_info']=$user_info;
        echo json_encode($data);
   }
   //获取广告方式，现在已固定为定向引流和定向曝光
   public function get_ad_type(){
        $ad_type_list=M('ad_type')->select();
        foreach ($ad_type_list as $key => $value) {
           $ad_type[$key]['id'] = $value['id'];
           $ad_type[$key]['title'] = $value['title'];
           $ad_type[$key]['checked'] = false;
           //$banner[$key]['ad_link'] = $value['ad_link'];
        }
        $data['ad_type']=$ad_type;
        echo json_encode($data);
   }
   //获取用户openid
    public function get_openid(){
        $code=I('request.code');
        $appid = 'wxcd8cb69e4c15cbfb'; // 小程序APPID
        $secret = 'a2383fcb0f92a465f718875850e2bff1'; // 小程序secret
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';    
        //echo $url;echo $code;  
        $res=json_decode(file_get_contents($url));
        //var_dump($res);
        $data['openid']=$res->openid;
        //var_dump($data);
        echo json_encode($data); // 这里是获取到的信息
    }
    //新用户注册
    public function register(){
        if($_POST){
            $openid=$data['openid']=I('post.openid');
            //echo $openid;
            //判断用户是否已经注册
            $is_exist=M('usermember')->where(array('openid'=>$openid))->find();
            if($is_exist){
                //$data['last_login']=time();
                //M('users')->where(array('user_id'=>$is_exist['user_id']))->save($data);
                $json['status']=1;
            }else{
                if($openid!='undefined'){
                    $popenid=I('post.popenid');
                    if($popenid!=""&&$popenid!=null){
                        $p_info=M('usermember')->where(array('openid'=>$popenid))->find();
                        $data['pid']=$p_info['id'];
                        // $pp_info=M('users')->where(array('user_id'=>$p_info['first_leader']))->field('user_id')->find();
                        // $data['second_leader']=$pp_info['user_id'];
                        // $ppp_info=M('users')->where(array('user_id'=>$pp_info['first_leader']))->field('user_id')->find();
                        // $data['third_leader']=$ppp_info['user_id'];
                        //查询所有优惠卷
                    }
                    $pid = I('pid');
                    if($pid !=''&&!empty($pid)){
                        $data['pid'] = $pid;
                    }
                    $data['username']=I('post.username');
                    $data['head_icon']=I('post.head_icon');
                    $data['addtime']=time();
                    $res=M('usermember')->add($data);
                    //$json['sql']=M('usermember')->getLastSql();
                    if($res){
                        $json['status']=2;
                    }
                }else{
                    $json['status']=3;
                }
            }
            echo json_encode($json);
        }
    }
    //判断用户是否是商家用户
    public function is_shop(){
        $openid=I('request.openid');
        //echo $openid;
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $is_shop=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        //var_dump($is_shop);
        if($is_shop['status']==2){
            $data['status']=2;
        }elseif($is_shop['status']==1){
            $data['status']=1;
        }else{
            $data['status']=0;
        }
        echo json_encode($data);
    }
    //获取店铺信息
    public function shop_info(){
        $openid=I('post.openid');
        //echo $openid;
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $title_img=explode(',',$shop_info['title_img']);
        $data['img']=SITE_URL.get_cover($title_img[0],'path');
        $data['title']=$shop_info['title'];
        $data['balance']=$shop_info['balance'];
        $data['sid'] = $shop_info['id'];
        echo json_encode($data);
    }
    //设置店铺的标签
    public function set_shop_tag(){
        $openid=I('post.openid');
        //echo $openid;
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $data['tag']=$shop_info['tag'].I('post.tag_name').',';
        //var_dump($data);
        $res=M('shop')->where(array('id'=>$shop_info['id']))->save($data);
        //var_dump(M('shop')->getLastSql());
        if($res){
            echo json_encode(1);
        }
    }
    //获取店铺完整信息
    public function get_shop_info(){
        $openid=I('post.openid');
        
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        //$data['user_info']=$user_info;
        if(I('post.id')!=''&&I('post.id')!='undefined'){
            $shop_info=M('shop')->where(array('id'=>I('post.id')))->find();
        }else{
            //echo I('post.id');
            $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        }
        
        $title_img=explode(',',rtrim($shop_info['title_img'],','));
        foreach($title_img as $k=>$v){
            $img[$k]['img']=SITE_URL.get_cover($v,'path');
        }
        $data['img']=$img;

        $data['imgs']=SITE_URL.get_cover($title_img[0],'path');

        $taga=explode(',',rtrim($shop_info['tag'],','));
        foreach($taga as $k=>$v){
            $tag[$k]['tag']=$v;
        }
        $data['tag']=$tag;
        
        $data['shop_info']=$shop_info;

        $data['left_up_number']=get_left_up_number($shop_info['id']);
        $data['left_in_number']=get_left_in_number($shop_info['id']);
        if(I('post.lat')&&I('post.lng')){
            $data['distance']=getDistance(I('post.lat'),I('post.lng'),$shop_info['latitude'],$shop_info['longitude']);
            $data['left_count']=get_left_up_number($shop_info['id'])+get_left_in_number($shop_info['id']);
            $data['yue_number']=get_up_yue_in_number($shop_info['id'])+get_in_yue_in_number($shop_info['id']);
        }
        echo json_encode($data);
    }
    //编辑店铺的标签
    public function edit_shop_tag(){
        $openid=I('post.openid');
        //echo $openid;
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $tag['tag']=I('post.tag0').','.I('post.tag1').','.I('post.tag2');
        $res=M('shop')->where(array('id'=>$shop_info['id']))->save($tag);
        //var_dump(M('shop')->getLastSql());
        if($res){
            echo json_encode(1);
        }
    }
    //获取店铺的标签
    public function get_shop_tag(){
        $openid=I('post.openid');
        //echo $openid;
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $taga=explode(',',rtrim($shop_info['tag'],','));
        foreach($taga as $k=>$v){
            $tag[$k]['tag']=$v;
        }
        $data['tag']=$tag;
        echo json_encode($data);
    }
    //获取用户信息
    public function get_user_info(){
        $openid=I('post.openid');
        //echo $openid;
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        //var_dump($user_info);
        $data['user_info']=$user_info;
        $count=M('user_activity')->where(array('user_id'=>$user_info['id'],'status'=>1))->count();
        $data['count']=$count;
        echo json_encode($data);
    }
    //用户申请提现
    public function apply_put_money(){
        $openid=I('post.openid');
        //echo $openid;
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $data['user_id']=$user_info['id'];
        $data['money']=I('post.balance');
        $data['addtime']=time();
        $data['status']=1;
        $res=M('user_put_money')->add($data);
        //扣除当前用户余额
        $balance['balance']=$user_info['balance']-$data['money'];
        $res2=M('usermember')->where(array('id'=>$user_info['user_id']))->save($balance);
        //if($res1&&$res2){
            $jdata['status']=1;
            echo json_encode($jdata);
        //}
    }
    //商家申请提现
    public function apply_shop_put_money(){
        $openid=I('post.openid');
        //echo $openid;
        // 用户信息
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        // 商家信息
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();

        $data['user_id']=$user_info['id'];
        $data['shop_id']=$shop_info['id'];
        $data['money']=I('post.balance');
        $data['addtime']=time();
        $data['status']=1;
        if($shop_info['withdraw_balance'] < $data['money'] || empty($data['money']))
        {
            //todo::可提现余额不足
            //返回错误信息
            $jdata['status']=0;
            echo json_encode($jdata,JSON_UNESCAPED_UNICODE);exit();
        }
        // 插入提现信息
        $res=M('shop_put_money')->add($data);
        //扣除总余额
        $balance['balance']=$shop_info['balance']-$data['money'];
        // 扣除可提现余额
        $balance['withdraw_balance'] = $shop_info['withdraw_balance'] - $data['money'];
        // 扣除可用本金
        $balance['shop_balance'] = $shop_info['shop_balance'] - $data['money'];
        $res2=M('shop')->where(array('id'=>$shop_info['id']))->save($balance);
        
            $jdata['status']=1;
            echo json_encode($jdata);
        
    }
    //充值支付申请
    public function charge_pay(){
        $total_price=$_POST['balance'];
        $order_sn=date('Ymd').rand(000000,999999);
        $params = [
          'appid' => 'wxcd8cb69e4c15cbfb',
          'mch_id' => '1561395241',
          // 随机串，32字符以内
          'nonce_str' => (string) mt_rand(10000, 99999), 
          // 商品名
          'body' =>"海芮芯", 
          // 订单号，自定义，32字符以内。多次支付时如果重复的话，微信会返回“重复下单”
          'out_trade_no' => $order_sn,
          // 订单费用，单位：分
          'total_fee' => $total_price*100,
          'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
          // 支付成功后的回调地址，服务端不一定真得有这个地址
          'notify_url' => 'https://myserver.com/notify.php',
          'trade_type' => 'JSAPI',
          // 小程序传来的OpenID
          'openid' => $_POST['openid'],
        ];
        //var_dump($params);
        // 按照要求计算sign
        ksort($params);
        $sequence = '';
        foreach ($params as $key => $value) {
          $sequence .= "$key=$value&";
        }
        $sequence = $sequence . "key=7mzZgSxBce8EOwXHNsq3OKKHEjVepEtw";
        $params['sign'] = strtoupper(md5($sequence));
        // 给微信发出的请求，整个参数是个XML
        $xml = '<xml>' . PHP_EOL;
        foreach ($params as $key => $value) {
          $xml .= "<$key>$value</$key>" . PHP_EOL;
        }
        $xml .= '</xml>';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.mch.weixin.qq.com/pay/unifiedorder');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        if (false === $output) {
          echo 'CURL Error:' . curl_error($ch);
        }
        // 下单成功的话，微信返回个XML，里面包含prepayID，提取出来
        if (0 === preg_match('/<prepay_id><\!\[CDATA\[(\w+)\]\]><\/prepay_id>/', $output, $match)) {
          echo $output;
          exit(0);
        }
        // 这里不是给小程序返回个prepayID，而是返回一个包含其他字段的JSON
        // 这个JSON小程序自己也可以生成，放在服务端生成是出于两个考虑：
        // 
        // 1. 小程序的appid不用写在小程序的代码里，appid、secret信息全部由服务器管理，比较安全
        // 2. 计算paySign需要用到md5，小程序端使用的是JavaScript，没有内置的md5函数，放在服务端计算md5比较方便
        $prepayId = $match[1];
        $response= [
          'appId' => 'wxcd8cb69e4c15cbfb',
          // 随机串，32个字符以内
          'nonceStr' => (string) mt_rand(10000, 99999),
          // 微信规定
          'package' => 'prepay_id=' . $prepayId,
          'signType' => 'MD5',
          // 时间戳，注意得是字符串形式的
          'timeStamp' => (string) time(),
        ];
        $sequence = '';
        foreach ($response as $key => $value) {
          $sequence .= "$key=$value&";
        }
        $response['paySign'] = strtoupper(md5("{$sequence}key=7mzZgSxBce8EOwXHNsq3OKKHEjVepEtw"));
        $response['order_sn']=$order_sn;
        echo json_encode($response);
    }
    //充值成功
    public function charge_success(){
        $openid=I('post.openid');
        $user_info=M('usermember')->where(array('openid'=>$openid))->field('openid,id,username,head_icon')->find();
        $data['user_id']=$user_info['id'];
        $data['money']=I('post.balance');
        $data['order_sn']=I('post.order_sn');
        $data['addtime']=time();
        $res=M('shop_charge_record')->add($data);
        //增加店铺余额
        // 计算赠送比例
        $recharge_ration = C('RECHARGE_PRESENT_RATIO') ? C('RECHARGE_PRESENT_RATIO') : 0;
        $exposure_balance = floor($data['money'] * $recharge_ration) / 100;
        $total_balance = $data['money'] + $exposure_balance;
        $shop_balance = $data['money'];

        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $saveData = [
            'balance' => $total_balance + $shop_info['balance'],
            'shop_balance' => $shop_balance + $shop_info['shop_balance'],
            'exposure_balance' => $exposure_balance + $shop_info['exposure_balance']
        ];
        $res2=M('shop')->where(array('id'=>$shop_info['id']))->save($saveData);
        //if($res1&&$res2){
            $jdata['status']=1;
            echo json_encode($jdata);
        //}
    }
    //获取广告详情的二维码
    public function get_share_code(){
        header('content-type:text/html;charset=utf-8');
        $ad_id=I('post.id');
        //配置APPID、APPSECRET
        $APPID = "wxcd8cb69e4c15cbfb"; 
        $APPSECRET =  "a2383fcb0f92a465f718875850e2bff1"; 
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
        //缓存access_token
         session_start();
         $_SESSION['access_token'] = "";
         $_SESSION['expires_in'] = 0;
         $ACCESS_TOKEN = "";
         if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
         {
             $json = accesshttpRequest( $access_token );
             $json = json_decode($json,true);
             // var_dump($json);
             $_SESSION['access_token'] = $json['access_token'];
             $_SESSION['expires_in'] = time()+7200;
             $ACCESS_TOKEN = $json["access_token"];
         } 
         else{
             $ACCESS_TOKEN =  $_SESSION["access_token"]; 
         }
        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$ACCESS_TOKEN."";
        $path = "pages/user/adv_detail/adv_detail";
        $param = json_encode(array("scene"=>$ad_id,"page"=>"$path","width"=> 150));
        //var_dump($param);
        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");
        //var_dump($result);
        //生成二维码
        file_put_contents("qrcode.jpg", $result);
//        $base64_image ="data:image/jpeg;base64,".base64_encode( $result );
        $img_url = SITE_URL."qrcode.jpg";
        //return $img_url;
        //echo $qcode;
        $data['access_token']=$ACCESS_TOKEN;
        $data['code']=$img_url;
        echo json_encode($data);
    }
    public function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
    //添加投放广告
    public function add_ad(){
        $openid=I('post.openid');
        $user_info=M('usermember')->where(array('openid'=>$openid))->field('openid,id,username,head_icon')->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $data['shop_id']=$shop_info['id'];
        $data['tou_shop_id']=I('post.shop_id');
        $data['ad_type']=I('post.ad_type');
        $data['region']=I('post.region');
        $data['shop_select']=I('post.shop_select');
        $data['ad_img_id']=I('post.ad_img_id');
        $data['video_id']=I('post.video_id');
        $data['text']=I('post.text');
        $data['startdate']=I('post.startdate');
        $data['enddate']=I('post.enddate');
         $data['starttime']=strtotime(I('post.startdate'));
        $data['endtime']=strtotime(I('post.enddate'));
        $data['number']=I('post.number');
        $data['money']=I('post.money');
        $data['total_money']=I('post.total_money');
        $data['status']=1;
        $data['add_type']=1;
        $data['addtime']=time();
        //如果用户选择了活动圈，添加活动圈记录
        $res=M('shop_ad')->add($data);

        //如果用户选择了活动圈，添加活动圈记录
        $activity=I('post.activity_select');
        //echo $activity;
        $activity_id=explode(',',$activity);
        $last_id=M('shop_ad')->order('id desc')->find();
        foreach($activity_id  as $v){
            if($v==1){
                $a['ad_id']=$last_id['id'];
                $a['content']=I('post.one_text');
                M('shop_activity')->add($a);
            }elseif($v==2){
                $a['ad_id']=$last_id['id'];
                $a['content']='买赠活动,买'.I('post.two_text_first').'赠'.I('post.two_text_later');
                M('shop_activity')->add($a);
            }
            elseif($v==3){
                $a['ad_id']=$last_id['id'];
                $a['content']='满减活动,满'.I('post.three_text_first').'减'.I('post.three_text_later');
                M('shop_activity')->add($a);
            }elseif($v==4){
                $a['ad_id']=$last_id['id'];
                $a['content']='充值活动,充'.I('post.four_text_first').'送'.I('post.four_text_later');
                M('shop_activity')->add($a);
            }elseif($v==5){
                $a['ad_id']=$last_id['id'];
                $a['content']='减免活动,满'.I('post.four_text_first').'免'.I('post.four_text_later');
                M('shop_activity')->add($a);
            }
        }

        //生成广告二维码并保存
        $APPID = "wxcd8cb69e4c15cbfb"; 
        $APPSECRET =  "a2383fcb0f92a465f718875850e2bff1"; 
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
        //缓存access_token
         session_start();
         $_SESSION['access_token'] = "";
         $_SESSION['expires_in'] = 0;
         $ACCESS_TOKEN = "";
         if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
         {
             $json = accesshttpRequest( $access_token );
             $json = json_decode($json,true);
             // var_dump($json);
             $_SESSION['access_token'] = $json['access_token'];
             $_SESSION['expires_in'] = time()+7200;
             $ACCESS_TOKEN = $json["access_token"];
         } 
         else{
             $ACCESS_TOKEN =  $_SESSION["access_token"]; 
         }
        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$ACCESS_TOKEN."";
        $path = "pages/user/adv_detail/adv_detail";
        $param = json_encode(array("scene"=>$last_id['id'],"page"=>"$path","width"=> 150));
        //var_dump($param);
        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");
        //var_dump($result);
        //生成二维码
        file_put_contents("./qrcode/qrcode".$last_id['id'].".jpg", $result);
//        $base64_image ="data:image/jpeg;base64,".base64_encode( $result );
        $img_url = SITE_URL."qrcode/qrcode".$last_id['id'].".jpg";
        $img['code']=$img_url;
        M('shop_ad')->where(array('id'=>$last_id['id']))->save($img);

    }
    //用户添加模板广告
    public function add_tem_ad(){
        $openid=I('post.openid');
        $user_info=M('usermember')->where(array('openid'=>$openid))->field('openid,id,username,head_icon')->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $data['shop_id']=$shop_info['id'];
        $data['ad_type']=I('post.ad_type');
        $data['region']=I('post.region');
        $data['shop_select']=I('post.shop_select');
        $data['ad_img_id']=I('post.ad_img_id');
        $data['video_id']=I('post.video_id');
        $data['text']=I('post.text');
        $data['startdate']=I('post.startdate');
        $data['enddate']=I('post.enddate');
        $data['starttime']=strtotime(I('post.startdate'));
        $data['endtime']=strtotime(I('post.enddate'));
        $data['number']=I('post.number');
        $data['money']=I('post.money');
        $data['total_money']=I('post.total_money');
        $data['status']=1;
        $data['add_type']=2;
        $data['addtime']=time();
        $res=M('shop_ad')->add($data);
        //如果用户选择了活动圈，添加活动圈记录
        $activity=I('post.activity_select');
        //echo $activity;
        $activity_id=explode(',',$activity);
        $last_id=M('shop_ad')->order('id desc')->find();
        foreach($activity_id  as $v){
            if($v==1){
                $a['ad_id']=$last_id['id'];
                $a['content']=I('post.one_text');
                M('shop_activity')->add($a);
            }elseif($v==2){
                $a['ad_id']=$last_id['id'];
                $a['content']='买赠活动,买'.I('post.two_text_first').'赠'.I('post.two_text_later');
                M('shop_activity')->add($a);
            }
            elseif($v==3){
                $a['ad_id']=$last_id['id'];
                $a['content']='满减活动,满'.I('post.three_text_first').'减'.I('post.three_text_later');
                M('shop_activity')->add($a);
            }elseif($v==4){
                $a['ad_id']=$last_id['id'];
                $a['content']='充值活动,充'.I('post.four_text_first').'送'.I('post.four_text_later');
                M('shop_activity')->add($a);
            }elseif($v==5){
                $a['ad_id']=$last_id['id'];
                $a['content']='减免活动,满'.I('post.four_text_first').'免'.I('post.four_text_later');
                M('shop_activity')->add($a);
            }
        }
        //生成广告二维码并保存
        $APPID = "wxcd8cb69e4c15cbfb"; 
        $APPSECRET =  "a2383fcb0f92a465f718875850e2bff1"; 
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
        //缓存access_token
         session_start();
         $_SESSION['access_token'] = "";
         $_SESSION['expires_in'] = 0;
         $ACCESS_TOKEN = "";
         if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
         {
             $json = accesshttpRequest( $access_token );
             $json = json_decode($json,true);
             // var_dump($json);
             $_SESSION['access_token'] = $json['access_token'];
             $_SESSION['expires_in'] = time()+7200;
             $ACCESS_TOKEN = $json["access_token"];
         } 
         else{
             $ACCESS_TOKEN =  $_SESSION["access_token"]; 
         }
        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$ACCESS_TOKEN."";
        $path = "pages/user/adv_detail/adv_detail";
        $param = json_encode(array("scene"=>$last_id['id'],"page"=>"$path","width"=> 150));
        //var_dump($param);
        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");
        //var_dump($result);
        //生成二维码
        file_put_contents("./qrcode/qrcode".$last_id['id'].".jpg", $result);
//        $base64_image ="data:image/jpeg;base64,".base64_encode( $result );
        $img_url = SITE_URL."qrcode/qrcode".$last_id['id'].".jpg";
        $img['code']=$img_url;
        M('shop_ad')->where(array('id'=>$last_id['id']))->save($img);
    }
    //获取当前用户添加的模板广告
    public function get_tem_ad(){
        $openid=I('post.openid');
        $user_info=M('usermember')->where(array('openid'=>$openid))->field('id')->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->field('id')->find();
        $ad_list=M('shop_ad')->where(array('shop_id'=>$shop_info['id'],'add_type'=>2,'ad_type'=>I('post.ad_type')))->select();
        foreach($ad_list as $k=>$v){
            $list[$k]['id']=$v['id'];
            $list[$k]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[$k]['video']=SITE_URL.get_cover($v['video_id'],'path');
            $list[$k]['title']=$v['text'];
            $list[$k]['time']=date('Y-m-d H:i',$v['addtime']);
        }
        $data['user_message']=$list;
        echo json_encode($data);
    }
    //获取广告信息
    public function get_ad_info(){
        $id=I('post.id');
        ////echo $id;die();
        $info=M('shop_ad')->where(array('id'=>$id))->find();
        $data['info']=$info;
        $data['img']=SITE_URL.get_cover($info['ad_img_id'],'path');

        $title="";$phone="";$address="";
        $shop_id=explode(',',$info['shop_select']);
        foreach($shop_id as $v){
            $one_shop_info=M('shop')->where(array('id'=>$v))->field('title,phone,address')->find();
            $title.=$one_shop_info['title'].',';
            $phone.=$one_shop_info['phone'].',';
            $address.=$one_shop_info['address'].',';
        }
        $data['title']=$title; $data['phone']=$phone;$data['address']=$address;
        $shopinfo=M('shop')->where(array('id'=>$info['shop_id']))->find();
        $data['shopinfo']=$shopinfo;
        //判断用户距离
        if(I('post.latitude')&&I('post.longitude')){
            $data['distance']=getDistance(I('post.latitude'),I('post.longitude'),$shopinfo['latitude'],$shopinfo['longitude']);
            $limit=M('config')->where(array('name'=>'RED_DISTANCE'))->find();
            $data['red_distance']=$limit['value'];
        }
        echo json_encode($data);
    }
    //获取店铺详情页面
    public function store_detail(){
        $id=I('post.id');
        $info=M('shop')->where(array('id'=>$id))->find();
        $data['info']=$info;
         $taga=explode(',',rtrim($info['tag'],','));
        foreach($taga as $k=>$v){
            $tag[$k]['tag']=$v;
        }
        $data['tag']=$tag;
        $title_img=explode(',',$info['title_img']);
        $data['img']=SITE_URL.get_cover($title_img[0],'path');
        echo json_encode($data);
    }
    //获取用户一天假模板
    public function get_template_ad(){
        $type=M('category')->where(array('pid'=>0))->select();
        foreach($type as $k=> $v){
            $list[$k]['id']=$v['id'];
            $list[$k]['name']=$v['title'];
            $ad=M('template')->where(array('type_id'=>$v['id'],'ad_type'=>I('post.ad_type')))->select();
            foreach($ad as $key =>$value){
                $list[$k]['data'][$key]['id']=$value['id'];
                $list[$k]['data'][$key]['imgs']=SITE_URL.get_cover($value['img'],'path');
                $list[$k]['data'][$key]['own_title']="买赠活动";
                $list[$k]['data'][$key]['own_num']="买赠数量";
                $list[$k]['data'][$key]['own_UP1']="买";
                $list[$k]['data'][$key]['own_UP']="赠";
                $list[$k]['data'][$key]['own_name']="赠品名称";
            }
        }
        $data['second_nav']=$list;
        echo json_encode($data);
    }
    //获取用户添加定向引流广告
    public function get_shop_ad_xiang(){
        $openid=I('post.openid');
        //echo $openid;die();
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $all=M('shop_ad')->where(array('shop_id'=>$shop_info['id'],'ad_type'=>1))->select();
        $list[1]['id']=1;
        $list[1]['name']='全部';
        foreach($all as $key=>$v){
            $list[1]['data'][$key]['id']=$v['id'];
            $list[1]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[1]['data'][$key]['title']=$v['text'];
            $list[1]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[1]['data'][$key]['status']=$v['status'];
        }

        $all2=M('shop_ad')->where(array('shop_id'=>$shop_info['id'],'ad_type'=>1,'status'=>1))->select();
        $list[2]['id']=2;
        $list[2]['name']='待审核';
        foreach($all2 as $key=>$v){
            $list[2]['data'][$key]['id']=$v['id'];
            $list[2]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[2]['data'][$key]['title']=$v['text'];
            $list[2]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[2]['data'][$key]['status']=$v['status'];
        }

        $all3=M('shop_ad')->where(array('shop_id'=>$shop_info['id'],'ad_type'=>1,'status'=>3))->select();
        $list[3]['id']=3;
        $list[3]['name']='投放中';
        foreach($all3 as $key=>$v){
            $list[3]['data'][$key]['id']=$v['id'];
            $list[3]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[3]['data'][$key]['title']=$v['text'];
            $list[3]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[3]['data'][$key]['status']=$v['status'];
        }

        $all4=M('shop_ad')->where(array('shop_id'=>$shop_info['id'],'ad_type'=>1,'status'=>4))->select();
        $list[4]['id']=4;
        $list[4]['name']='已完成';
        foreach($all4 as $key=>$v){
            $list[4]['data'][$key]['id']=$v['id'];
            $list[4]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[4]['data'][$key]['title']=$v['text'];
            $list[4]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[4]['data'][$key]['status']=$v['status'];
        }

        $data['list']=$list;
        echo json_encode($data);

    }
    //获取用户添加定向曝光广告
    public function get_shop_ad_pu(){
        $openid=I('post.openid');
        //echo $openid;die();
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $all=M('shop_ad')->where(array('shop_id'=>$shop_info['id'],'ad_type'=>2))->select();
        $list[1]['id']=1;
        $list[1]['name']='全部';
        foreach($all as $key=>$v){
            $list[1]['data'][$key]['id']=$v['id'];
            $list[1]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[1]['data'][$key]['title']=$v['text'];
            $list[1]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[1]['data'][$key]['status']=$v['status'];
        }

        $all2=M('shop_ad')->where(array('shop_id'=>$shop_info['id'],'ad_type'=>2,'status'=>1))->select();
        $list[2]['id']=2;
        $list[2]['name']='待审核';
        foreach($all2 as $key=>$v){
            $list[2]['data'][$key]['id']=$v['id'];
            $list[2]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[2]['data'][$key]['title']=$v['text'];
            $list[2]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[2]['data'][$key]['status']=$v['status'];
        }

        $all3=M('shop_ad')->where(array('shop_id'=>$shop_info['id'],'ad_type'=>2,'status'=>3))->select();
        $list[3]['id']=3;
        $list[3]['name']='投放中';
        foreach($all3 as $key=>$v){
            $list[3]['data'][$key]['id']=$v['id'];
            $list[3]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[3]['data'][$key]['title']=$v['text'];
            $list[3]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[3]['data'][$key]['status']=$v['status'];
        }

        $all4=M('shop_ad')->where(array('shop_id'=>$shop_info['id'],'ad_type'=>2,'status'=>4))->select();
        $list[4]['id']=4;
        $list[4]['name']='已完成';
        foreach($all4 as $key=>$v){
            $list[4]['data'][$key]['id']=$v['id'];
            $list[4]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[4]['data'][$key]['title']=$v['text'];
            $list[4]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[4]['data'][$key]['status']=$v['status'];
        }
        $data['list']=$list;
        echo json_encode($data);
    }
    //获取我投放的广告
    public function to_ad(){
        $openid=I('post.openid');
        //echo $openid;die();
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $shop_id=$shop_info['id'];
        $all=M('shop_ad')->where("shop_select like '%$shop_id%' and add_type=1")->select();
        $list[1]['id']=1;
        $list[1]['name']='全部';
        foreach($all as $key=>$v){
            $list[1]['data'][$key]['id']=$v['id'];
            $list[1]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[1]['data'][$key]['title']=$v['text'];
            $list[1]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[1]['data'][$key]['status']=$v['status'];
        }

        $all4=M('shop_ad')->where("shop_select like '%$shop_id%'")->where(array('status'=>3))->select();
        $list[2]['id']=2;
        $list[2]['name']='投放中';
        foreach($all4 as $key=>$v){
            $list[2]['data'][$key]['id']=$v['id'];
            $list[2]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[2]['data'][$key]['title']=$v['text'];
            $list[2]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[2]['data'][$key]['status']=$v['status'];
        }

        $all3=M('shop_ad')->where("shop_select like '%$shop_id%'")->where(array('status'=>4))->select();
        $list[3]['id']=3;
        $list[3]['name']='已完成';
        foreach($all3 as $key=>$v){
            $list[3]['data'][$key]['id']=$v['id'];
            $list[3]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[3]['data'][$key]['title']=$v['text'];
            $list[3]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[3]['data'][$key]['status']=$v['status'];
        }
        $data['list']=$list;
        echo json_encode($data);

    }
    //获取别人投放我的广告
    public function from_ad(){
        $openid=I('post.openid');
        //echo $openid;die();
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $shop_id=$shop_info['id'];
        $all=M('shop_ad')->where(array('shop_id'=>$shop_id,'add_type'=>1))->select();
        $list[1]['id']=1;
        $list[1]['name']='全部';
        foreach($all as $key=>$v){
            $list[1]['data'][$key]['id']=$v['id'];
            $list[1]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[1]['data'][$key]['title']=$v['text'];
            $list[1]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[1]['data'][$key]['status']=$v['status'];
        }

        $all4=M('shop_ad')->where(array('shop_id'=>$shop_id))->where(array('status'=>3))->select();
        $list[2]['id']=2;
        $list[2]['name']='投放中';
        foreach($all4 as $key=>$v){
            $list[2]['data'][$key]['id']=$v['id'];
            $list[2]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[2]['data'][$key]['title']=$v['text'];
            $list[2]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[2]['data'][$key]['status']=$v['status'];
        }

        $all3=M('shop_ad')->where(array('shop_id'=>$shop_id))->where(array('status'=>4))->select();
        $list[3]['id']=3;
        $list[3]['name']='已完成';
        foreach($all3 as $key=>$v){
            $list[3]['data'][$key]['id']=$v['id'];
            $list[3]['data'][$key]['imgs']=SITE_URL.get_cover($v['ad_img_id'],'path');
            $list[3]['data'][$key]['title']=$v['text'];
            $list[3]['data'][$key]['time']=$v['startdate'].'到'.$v['enddate'];
            $list[3]['data'][$key]['status']=$v['status'];
        }
        $data['list']=$list;
        echo json_encode($data);

    }
    //获取用户红包记录
    public function get_red_record(){
        $openid=I('post.openid');
        //echo $openid;die();
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $list=M('red_record')->where(array('user_id'=>$user_info['id']))->select();
        $total=0;
        foreach($list as $k=>$v){
            $record[$k]['id']=$v['id'];
            $record[$k]['title']='红包领取';
            $record[$k]['money']='+'.$v['money'];
            $shop_info=M('shop')->where(array('id'=>$v['shop_id']))->find();
            $record[$k]['store']='+'.$v['money'];
            $total+=$v['money'];
        }
        $data['record']=$record;
        $data['total']=$total;
        echo json_encode($data);
    }
    //获取用户的资金记录
    public function get_money_record(){
        $openid=I('post.openid');
        //echo $openid;die();
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $red=M('red_record')->where(array('user_id'=>$user_info['id']))->select();
        $list[0]['typeid']=1;
        $list[0]['title']='红包记录';
        foreach($red as $k=>$v){
            $list[0]['data'][$k]['id']=$v['id'];
            $list[0]['data'][$k]['title']='红包领取';
            $list[0]['data'][$k]['money']='+'.$v['money'];
            $list[0]['data'][$k]['time']=date('Y-m-d',$v['addtime']);
        }

        $put=M('user_put_money')->where(array('user_id'=>$user_info['id']))->select();
        $list[1]['typeid']=2;
        $list[1]['title']='提现记录';
        foreach($put as $k=>$v){
           $list[1]['data'][$k]['id']=$v['id'];
            $list[1]['data'][$k]['title']='提现';
            $list[1]['data'][$k]['money']='-'.$v['money'];
            $list[1]['data'][$k]['time']=date('Y-m-d',$v['addtime']);
        }
        $data['list']=$list;
        echo json_encode($data);
    }
    //获取商家的余额 
    public function get_shop_money(){
        $openid=I('post.openid');
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        $data['shop_info']=$shop_info;
        //查询冻结资金
        $time=time();
        $shop_id=$shop_info['id'];
        $total_money=0;
        $list=M('shop_ad')->where("shop_select like '%$shop_id%' and endtime > $time and is_money=1 and ad_type=2 and add_type=1 and status=3")->select();
        $limit=M('config')->where(array('name'=>'UP_SHOP_LIMIT'))->find();
        foreach($list as  $v){
            $count=count(explode(',',$v['shop_select']));
            $total_money+=($v['total_money']/$count)*$limit['value'];
        }
        $data['total_money']=$total_money;
        //var_dump($list);
        //var_dump(M('shop_ad')->getLastSql());
        echo json_encode($data);
    }
    //获取商家的资金记录
    public function get_money_info(){
         $openid=I('post.openid');
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        //定向曝光资金明细
        $shop_id=$shop_info['id'];
        $adlist=M('shop_ad')->where("shop_select like '%$shop_id%' and ad_type=2 and add_type=1")->select();
        //var_dump($adlist);
        $money=0;
        $limit=M('config')->where(array('name'=>'UP_SHOP_LIMIT'))->find();
        foreach($adlist as $k=>$v){
            $count=count(explode(',',$v['shop_select']));
            $money+=($v['total_money']/$count)*$limit['value'];
            $list[0]['data'][$k]['id']=$v['id'];
            $list[0]['data'][$k]['title']='广告收入';
            $list[0]['data'][$k]['time']=$v['enddate'];
            $list[0]['data'][$k]['money']=($v['total_money']/$count)*$limit['value'];

        }
        $list[0]['id']=1;
        $list[0]['name']='定向曝光';
        $list[0]['totol']='定向曝光总收入';
        $list[0]['money']=$money;


        $money=0;
        $record=M('shop_money_record')->where(array('shop_id'=>$shop_info['id']))->select();
        foreach($record as $k=>$v){
            $list[1]['data'][$k]['id']=$v['id'];
            $list[1]['data'][$k]['title']='用户扫码广告收入';
            $list[1]['data'][$k]['time']=date('Y-m-d',$v['addtime']);
            $list[1]['data'][$k]['money']='+'.$v['money'];
            $money+=$v['money'];
        }
        $list[1]['id']=2;
        $list[1]['name']='定向引流';
        $list[1]['totol']='定向引流总收入';
        $list[1]['money']=$money;

        $data['list']=$list;
        echo json_encode($data);
    }
    //获取用户的提现申请
    public function cash_detail(){
        $openid=I('post.openid');
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        $shop_info=M('shop')->where(array('user_id'=>$user_info['id']))->find();
        //定向曝光资金明细
        $shop_id=$shop_info['id'];
        $adlist=M('shop_put_money')->where(array('shop_id'=>$shop_id))->select();
        $money=0;
        foreach($adlist as $k=>$v){
            $list[0]['data'][$k]['id']=$v['id'];
            if($v['status']==1){
                $list[0]['data'][$k]['title']='申请提现(审核中)';
            }elseif($v['status']==2){
                $list[0]['data'][$k]['title']='申请提现(已提现)';
            }elseif($v['status']==3){
                $list[0]['data'][$k]['title']='申请提现(已驳回)';
            }
            $list[0]['data'][$k]['time']=date('Y-m-d',$v['addtime']);
            $list[0]['data'][$k]['money']=$v['money'];
            $money+=$v['money'];
        }
        $list[0]['id']=1;
        $list[0]['name']='提现记录';
        $list[0]['totol']='总提现金额';
        $list[0]['money']=$money;

        $data['list']=$list;
        echo json_encode($data);
    }
    //用户点击获取红包，同时领取红包后计算每个商家的返利金额
    public function get_red_info(){
        $openid=I('post.openid');
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();
        //todo::距离判断
        //获取广告信息
        $id=I('post.id');
        $ad_info=M('shop_ad')->where(array('id'=>$id))->find();
        //判断用户是否已经领取当前红包
        $is_ling=M('red_record')->where(array('ad_id'=>$id,'user_id'=>$user_info['id']))->find();
        if($is_ling){
             $data['status']=2;
        }else{
            //返还用户获取红包金额,保存用户金额
            $user_limit=M('config')->where(array('name'=>'IN_USER_LIMIT'))->find();
            $user_balance['balance']=$user_info['balance']+$ad_info['money']*$user_limit['value'];
            M('usermember')->where(array('id'=>$user_info['id']))->save($user_balance);
            //添加用户领取记录
            $urecord['ad_id']=$id;
            $urecord['user_id']=$user_info['id'];
            $urecord['money']=$ad_info['money']*$user_limit['value'];
            $urecord['addtime']=time();
            M('red_record')->add($urecord);

            //添加用户优惠券
            $jlist=M('shop_activity')->where(array('ad_id'=>$id))->select();
            foreach($jlist as $v){
                $activity['user_id']=$user_info['id'];
                $activity['content']=$v['content'];
                $activity['ad_id']=$id;
                $activity['addtime']=time();
                M('user_activity')->add($activity);
            }
            //返还商家获取红包金额
            $shop_limit=M('config')->where(array('name'=>'IN_SHOP_LIMIT'))->find();
            //所有商家返还金额
            $shop_id=explode(',',$ad_info['shop_select']);
            foreach($shop_id as $v){
                $shop_info=M('shop')->where(array('id'=>$v))->find();
                $shop_balance['balance']=$shop_info['money']+$ad_info['money']*$shop_limit['value'];
                M('shop')->where(array('id'=>$v))->save($shop_balance);
                $record['title']='用户扫码领取红包';
                $record['money']=$ad_info['money']*$shop_limit['value'];
                $record['shop_id']=$v;
                $record['addtime']=time();
                M('shop_money_record')->add($record);
            }
            //给商户添加用户扫码记录
            $qrcode['user_id'] = $user_info['id'];
            $qrcode['shop_id'] = $ad_info['shop_id']; //商户id 具体门店增加字段store_id
            $qrcode['ad_type'] = $ad_info['ad_type'];
            $qrcode['title'] = '用户扫码领取红包记录';
            $qrcode['addtime'] = time();
            M('ShopQrcodeRecord')->add($qrcode);
            $data['status']=1;
            //todo:根据订单分屏插入商户粉丝表
            $fansData = [
                'sid' => '',// 商户ID
                'mid' => '',// 用户ID
                'order_list_id' => '',// 订单分屏编号
            ];
//            M('ShopFans')->add($fansData);
           
        }
        
        echo json_encode($data);
    }
    //获取用户活动卷
    public function get_activity_list(){
        $openid=I('post.openid');
        $user_info=M('usermember')->where(array('openid'=>$openid))->find();

        $red=M('user_activity')->where(array('user_id'=>$user_info['id'],'status'=>1))->select();
        $list[0]['typeid']=1;
        $list[0]['title']='待使用';
        foreach($red as $k=>$v){
            $ad_info=M('shop_ad')->where(array('id'=>$v['ad_id']))->field("shop_id")->find();
            $shop_info=M('shop')->where(array('id'=>$ad_info['shop_id']))->field('title')->find();
            $list[0]['data'][$k]['id']=$v['id'];
            $list[0]['data'][$k]['title']=$shop_info['title'];
            $list[0]['data'][$k]['des']=$v['content'];
            $list[0]['data'][$k]['time']='';
            $list[0]['data'][$k]['use']='线下店面使用';
            $list[0]['data'][$k]['status']=1;
        }

        $put=M('user_activity')->where(array('user_id'=>$user_info['id'],'status'=>2))->select();
        $list[1]['typeid']=2;
        $list[1]['title']='已使用';
        foreach($put as $k=>$v){
           $ad_info=M('shop_ad')->where(array('id'=>$v['ad_id']))->field("shop_id")->find();
            $shop_info=M('shop')->where(array('id'=>$ad_info['shop_id']))->field('title')->find();
            $list[1]['data'][$k]['id']=$v['id'];
            $list[1]['data'][$k]['title']=$shop_info['title'];
            $list[1]['data'][$k]['des']=$v['content'];
            $list[1]['data'][$k]['time']='';
            $list[1]['data'][$k]['use']='线下店面使用';
            $list[1]['data'][$k]['status']=2;
        }
        $data['list']=$list;
        echo json_encode($data);
    }
    //获取活动券信息，同时生成核销码
    public function get_activity_info(){
        $id=I('post.id');
        $info=M('user_activity')->where(array('id'=>$id))->find();

        $ad_info=M('shop_ad')->where(array('id'=>$info['ad_id']))->field("shop_id")->find();

        $shop_info=M('shop')->where(array('id'=>$ad_info['shop_id']))->field('title,phone,address')->find();

        $data['des']=$info['content'];
        $data['title']=$shop_info['title'];
        $data['phone']=$shop_info['phone'];
        $data['address']=$shop_info['address'];

        //生成广告二维码并保存
        $APPID = "wxcd8cb69e4c15cbfb"; 
        $APPSECRET =  "a2383fcb0f92a465f718875850e2bff1"; 
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
        //缓存access_token
         session_start();
         $_SESSION['access_token'] = "";
         $_SESSION['expires_in'] = 0;
         $ACCESS_TOKEN = "";
         if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() > $_SESSION['expires_in']))
         {
             $json = accesshttpRequest( $access_token );
             $json = json_decode($json,true);
             // var_dump($json);
             $_SESSION['access_token'] = $json['access_token'];
             $_SESSION['expires_in'] = time()+7200;
             $ACCESS_TOKEN = $json["access_token"];
         } 
         else{
             $ACCESS_TOKEN =  $_SESSION["access_token"]; 
         }
        //构建请求二维码参数
        //path是扫描二维码跳转的小程序路径，可以带参数?id=xxx
        //width是二维码宽度
        $qcode ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$ACCESS_TOKEN."";
        $path = "pages/destoryactivity/destoryactivity";
        $param = json_encode(array("scene"=>$id,"page"=>"$path","width"=> 150));
        //var_dump($param);
        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");
        //var_dump($result);
        //生成二维码
        file_put_contents("qrcode.jpg", $result);
//        $base64_image ="data:image/jpeg;base64,".base64_encode( $result );
        $img_url = SITE_URL."qrcode.jpg";
        
        $data['code']=$img_url;
        echo json_encode($data);

    }
    //核销活动卷，改变状态
    public function destory_activity(){
        $id=I('post.id');
        $data['status']=2;
        M('user_activity')->where(array('id'=>$id))->save($data);

    }
    //获取地图商家列表
    public function get_map_shop_list(){
        $list=M('shop')->where(array('status'=>2))->select();
        foreach($list as $k=>$v){
            $markers[$k]['id']=$v['id'];
            $markers[$k]['latitude']=$v['latitude'];
            $markers[$k]['longitude']=$v['longitude'];
        }
        $data['markers']=$markers;
        echo json_encode($data);
    }
    //编辑广告模板信息
    public function save_tem_ad(){
        $id=I('post.id');
        $data['region']=I('post.region');
        $data['shop_select']=I('post.shop_select');
        $data['ad_img_id']=I('post.ad_img_id');
        $data['text']=I('post.text');
        $data['startdate']=I('post.startdate');
        $data['enddate']=I('post.enddate');
        $data['starttime']=strtotime(I('post.startdate'));
        $data['endtime']=strtotime(I('post.enddate'));
        $data['number']=I('post.number');
        $data['money']=I('post.money');
        $data['total_money']=I('post.total_money');
        $res=M('shop_ad')->where(array('id'=>$id))->save($data);
        if($res){
            echo json_encode(1);
        }
    }

    /**
     * 商户获取广告扫码记录
     */
    public function get_shop_qrcode_record()
    {
        $id = I('id');//商户id
      //  $ad_type = I('ad_type');//广告类型
        $list = M('shop_qrcode_record')->where(['shop_id'=>$id,'ad_type'=>1])->select();
        foreach ($list as &$v){
            $userInfo = M('usermember')->where(['id'=>$v['user_id']])->find();
            $v['user_info'] = $userInfo;
        }
        $lists = M('shop_qrcode_record')->where(['shop_id'=>$id,'ad_type'=>2])->select();
        foreach ($lists as &$v){
            $userInfo = M('usermember')->where(['id'=>$v['user_id']])->find();
            $v['user_info'] = $userInfo;
        }
        $data['type_noe'] = $list;
        $data['type_tow'] = $lists;
        echo json_encode($data);
    }


}